//
//  ImageAverage.m
//  QtiSight
//
//  Created by Jonathan Saggau on 6/25/06.
//  Copyright 2006 __MyCompanyName__. All rights reserved.
//

#import "ImageAverage.h"

@implementation ImageAverage

- (id)initWithImage:(NSImage *)img;
{
    if (![super init])
        return nil;
    theImage = img;
    isMonochrome = YES;
    avg = 0;
    return self;
}

- (id)init;
{
    NSImage* img = [[NSImage alloc] init];
    return [self initWithImage:img];
}

- (NSImage *)image;
{
    return theImage;
}

- (void)setImage:(NSImage *)image;
{
    theImage = image;
    [self averager];
    //only calc the average when the image changes!
}

- (BOOL)monochrome;
{
    return isMonochrome;
}

- (void)setMonochrome:(BOOL)mono;
{
    isMonochrome = mono;
}

- (int)average;
{
    return avg;
}

- (void)averager;
{
    NSBitmapImageRep *srcImageRep = [NSBitmapImageRep
                              imageRepWithData:[theImage TIFFRepresentation]];
    
    int w = [srcImageRep pixelsWide];
    int h = [srcImageRep pixelsHigh];
    //NSLog(@"W = %i", w);
    //NSLog(@"H = %i", h);
    int area = w*h;
    
    unsigned char *srcData = [srcImageRep bitmapData];
    // srcData is the straight-up binary bitmap data of the image
    unsigned char *pixel;
    int colorTotal = 0;
    
    int n = [srcImageRep bitsPerPixel] / 8;
    
    int x, y;
    if (isMonochrome) {
        for ( y = 0; y < h; y++ ) {
            for ( x = 0; x < w; x++ ) {
                pixel = srcData + n * (y * w + x);       
                colorTotal += (int)rint(pixel[0]);
                //grab just the Red pixel value
            }
        }
    } else {
        for ( y = 0; y < h; y++ ) {
            for ( x = 0; x < w; x++ ) {
                pixel = srcData + n * (y * w + x);       
                colorTotal += (int)rint((pixel[0] + pixel[1] + pixel[2]) / 3);
                //average all three pixels
            }
        }
    }
    avg = colorTotal / area;
}

@end
